/**
 * @author jcl_hqu
 * @date 2021/5/18 20:14
 */

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.text.csv.CsvData;
import cn.hutool.core.text.csv.CsvReader;
import cn.hutool.core.text.csv.CsvRow;
import cn.hutool.core.text.csv.CsvUtil;
import org.junit.Test;

import java.util.*;

/**
 * @description: 排队器
 *  事先将所有的就绪进程根据进程调度算法排成队列。
 * @param: null
 * @return:
 * @author jcl_hqu
 * @date: 2021/5/27 14:15
 */
public class Scheduler {
    private List<Job> jobList;

    // 初始化排队器
    public Scheduler(List<Job> jobList) {
        this.jobList=new LinkedList<>(jobList);
    }

    public Queue<Job> HRRN(double currentTime){
        // 计算响应比
        for (int i=0;i<jobList.size();i++){
            double arrival_time=jobList.get(i).arrival_time;
            double service_time=jobList.get(i).cpu_burst;
            jobList.get(i).setResponse_ratio((currentTime-arrival_time)/service_time+1);
        }

        // 按相应比大小，降序排列
        jobList.sort(new Comparator<Job>() {
            @Override
            public int compare(Job o1, Job o2) {
                if (o1.response_ratio< o2.response_ratio) return 1;
                if (o1.response_ratio==o2.response_ratio) return 0;
                return -1;
            }
        });
        Queue<Job> ready_queue=new LinkedList<>(jobList);
        return ready_queue;
    }

    public Queue<Job> RR(double currentTime){
        // 按到达时间大小，升序排列

        jobList.sort(new Comparator<Job>() {
            @Override
            public int compare(Job o1, Job o2) {
                if (o1.arrival_time< o2.arrival_time) return -1;
                if (o1.arrival_time==o2.arrival_time) return 0;
                return 1;
            }
        });
        Queue<Job> ready_queue=new LinkedList<>(jobList);
        return ready_queue;
    }
    // 测试代码，测试是否排好就绪队列
    public static void main(String[] args) {
        // 读取csv文件
        CsvReader reader = CsvUtil.getReader();
        CsvData data = reader.read(FileUtil.file(System.getProperty("user.dir") + "./EX4/res/testData.csv"));
        List<CsvRow> rows = data.getRows();
        List<Job> Jobs = new ArrayList<>();
        boolean flag = false;//不写第一行到VirtualProcess中
        for (CsvRow csvRow : rows) {
            if (!flag) {
                flag = true;
                continue;
            }
            Long id = Long.valueOf(csvRow.getRawList().get(0));
            Long arrival_time = Long.valueOf(csvRow.getRawList().get(1));
            Long service_time = Long.valueOf(csvRow.getRawList().get(2));
            Jobs.add(new Job(id, arrival_time, service_time));
        }
        Scheduler scheduler=new Scheduler(Jobs);
        Queue<Job> hrrn = scheduler.RR(1.0);
        for (Job h:
             hrrn) {
            System.out.println(h.arrival_time);
        }

    }
}
